<!--用户管理-->
<template>
  <div class="page-container">
    <ex_super_table_page v-bind="option" ref="SuperTablePage">
    </ex_super_table_page>

    <el-dialog title="费用明细" :visible.sync="dialogVisible" width="1000px">
      <ex-table-auto class="el-table-nowwarp" ref="resourceDownloadGridPanelEl"
        :url="'/fms-api/customer/CustomerAccountLogRpc/selectByBillDetailId.json?billDetailId=' + chooseRowBillDetailId"
        :autoFill="false" :autoPage="false" border>

        <el-table-column prop="serviceName" label="费用项" min-width="8">
        </el-table-column>
        <el-table-column prop="actualAmount" :label="$tt('计算参数')" min-width="16" align="center">
          <template slot-scope="scope">
            <bill_detail_info :row="scope.row"></bill_detail_info>
          </template>
        </el-table-column>
        <el-table-column prop="priceResult" label="费用总额" min-width="8">
          <template slot-scope="scope">
            {{ scope.row.priceResult.amount }}
          </template>
        </el-table-column>
        <el-table-column prop="happenTime" label="发生时间" min-width="8">
          <template slot-scope="scope">
            {{ $dateFormat(scope.row.happenTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" :label="$tt('label_fms_account_apply_status')" min-width="8" align="center">
          <template slot-scope="scope">
            {{ $enumShow(scope.row.status, 'FmsBillDetailStatus') }}
          </template>
        </el-table-column>
      </ex-table-auto>
      <span slot="footer" class="dialog_footer">
        <el-button @click="dialogVisible = false">{{ $tt('label_close') }}</el-button>
      </span>
    </el-dialog>

    <el-dialog :title="$tt('label_fms_account_log_credit_apply')" :visible.sync="dialogFormVisible" width="580px"
      height="200px" :close-on-click-modal="false">
      <el-form ref="formEl" :model="formValue" :rules="rules" label-width="120px" class="common-form-panel-div"
        style="padding: 0px 10px;">
        <ex_header_spiler :title="$tt('label_fms_account_log_apply_info')"></ex_header_spiler>
        <el-row>
          <el-col>
            <el-form-item :label="$tt('label_fms_account_cmp_as_customer')" prop="customerId">
              {{ '[' + formValue.customerCode + '] ' + formValue.customerName }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <el-form-item :label="$tt('label_fms_account_cmp_account_type')">
              {{ $tt('PmsProductTypeEnum__' + formValue.productType) }} - {{
                $tt('CurrencyTypeEnum__' +
                  formValue.currencyType)
              }} - {{ $tt('CustomerAccountTypeEnum__' + formValue.accountType) }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <el-form-item :label="$tt('label_fms_account_cmp_current_credit')">
              {{ formValue.oldCreditAmount }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <el-form-item :label="$tt('label_fms_account_cmp_adjust_as')">
              {{ formValue.newCreditAmount }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <el-form-item label="$tt('label_fms_account_cmp_adjust_reason')">
              {{ formValue.applyReason }}
            </el-form-item>
          </el-col>
        </el-row>

        <ex_header_spiler :title="$tt('label_fms_account_log_examine_result')"></ex_header_spiler>
        <el-row>
          <el-col>
            <el-form-item :label="$tt('label_fms_account_log_examine_result')">
              <el-radio-group v-model="formValue.type">
                <el-radio label="DONE">{{ $tt('label_fms_account_log_examine_success') }}</el-radio>
                <el-radio label="FAIL">{{ $tt('label_fms_account_log_examine_fail') }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row v-if="formValue.type == 'FAIL'">
          <el-col>
            <el-form-item :label="$tt('label_fms_account_log_examine_fail_reason')">
              <el-input v-model="formValue.refuseReason" style="width: 100%;"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">{{ $tt('label_fms_account_config_cancel') }}</el-button>
        <el-button type="primary" @click="submitForm">{{ $tt('label_fms_account_config_cancel') }}</el-button>
      </div>
    </el-dialog>


    <el-dialog title="导入" :visible.sync="importDiglogVisable" width="600px" :close-on-click-modal="false">
      <el-form :model="form" ref="form" label-position="top">
        <ex_header_spiler :title="$tt('label_batch_import')"></ex_header_spiler>
        <el-form-item>
          <el-button @click="downloadImportTemp" size="mini" type="primary" :disabled="loading" :loading="loading">{{
            $tt('label_download_import_template')
          }}<i class="el-icon-download el-icon--right"></i>
          </el-button>

          <el-upload v-auth="'oms_stock_head_query_import'" action="" :show-file-list="false" style="display: inline;"
            :http-request="uploadFile">
            <el-button slot="trigger" size="mini" type="primary">{{ $tt('label_import_excel') }}</el-button>
          </el-upload>
        </el-form-item>
        <ex_header_spiler title="导入模板说明"></ex_header_spiler>
        <el-form-item style="font-size: 13px">
          <label>导入模板中，除了金额，其他全部为文本类型单元格</label><br>
          <label>以下列举字段请使用对应的英文编码值</label><br>
          <lebel>字段说明：</lebel><br>
          <label>业务类型：MODIFY("调账"),SUPPLE("补款"),REFUND("退款"),WITHDRAW("提现"),CONSUME("消费"),PAYBACK("还款")；</label><br>
          <label>单据业务类型：INBOUND("入库单"),OUTBOUND("出库单"),STOCKTAKE("盘点单"),ERROR_MODIFY("异常调整单"),MODIFY_LOCATION("移库单"),
            REFUND("退货订单"),LEAVE_WAREHOUSE("退仓订单"), TENANT("仓租订单"), EXPRESS("快递订单"),BILL("账单") ；</label><br>
          <label>账户类型：CASH("预付款账户"), CREDIT("信用账户")；</label><br>
          <label>预付款币种：请输入币种，如 CNY</label><br>
          <label>信用账户类型：FIRST_TRANSPORT("头程"),LAST_TRANSPORT("尾程"), WAREHOUSE("仓储")；</label><br>
          <label>交易时间：格式为 yyyy-MM-dd HH:mm:ss ，如：2023-12-25 18:18:18</label><br>
        </el-form-item>
      </el-form>
    </el-dialog>



    <ex_super_dialog_form ref="addLogDialog" v-bind="addLogDialog" @afterSubmitSuccess="reload()">
    </ex_super_dialog_form>
    <ex_image_view ref="previewImage" style="width: 100px; height: 100px;display:none;"
      :src="previewUrls.length == 0 ? '' : previewUrls[0]" :preview-src-list="previewUrls" fit="scale-down">
    </ex_image_view>
  </div>
</template>
<script>

import business_function from "@/common/business_function";
let moduleName = "label_fms_account_log_account_statement"
import superTablePageFunction from '@/mixin/super-table-page-function';
import bill_detail_info from '@/component/fms/bill_detail_info.vue'

export default {

  title: moduleName,
  components: { bill_detail_info },

  mixins: [superTablePageFunction],
  data() {


    return {

      previewUrls: [],

      dialogVisible: false,
      chooseRowBillDetailId: 0,
      importDiglogVisable: false,

      loading: false,
      form: {},
      dialogFormVisible: false,
      dialogTitle: '',
      formValue: {
        'type': 'DONE'
      },
      rules: {},
      addLogDialog: {
        customClass: 'dialog_auto',
        submitUrl: '/fms-api/customer/CustomerAccountLogRpc/saveAccountLogBySelf.json',
        submitDataHandle: (data) => {
          const { files, ...other } = data
          other.logVoucher = _.isEmpty(files) ? null : _.head(files).filePath
          return other
        },
        form: {
          itemClass: "form_item_default", inputClass: "form_input_default",
          model: [
            {
              key: 'customerId', label: 'label_fms_account_cmp_as_customer', type: "common_customer_choose",
              keyExtra: { customerCode: 'customerCode', customerName: 'customerName' },
            },
            {
              key: 'accountId', label: 'label_account',
              render: (h, { data, item }) => {
                const controlFun = (params) => {
                  if (params.customerId) {
                    return true
                  } else {
                    return {
                      netStop: true,
                      focusInnerData: [],
                      warnning: this.$tt("tip_please_select_first_customer"),
                    }
                  }
                }
                const value = data[item.key]
                return <ex_select_auto value={value} onInput={e => this.$set(data, item.key, e)} class="form_input_default"
                  dependentId={data.customerId}
                  url='/fms-api/customer/CustomerAccountRpc/selectAccountByCustomerId.json'
                  option={item => ({
                    label: (item.accountType === 'CREDIT' ? (this.$enumShow(item.productType, 'PmsProductTypeEnum') + ' - ') : '') + `${this.$enumShow(item.currencyType, 'CurrencyTypeEnum')} - ${this.$enumShow(item.accountType, 'CustomerAccountTypeEnum')}`,
                    value: item.id
                  })}
                  urlParams={{ customerId: data.customerId, }}
                  urlControl={controlFun}
                />
              }
            },

            {
              key: 'modifyType', label: 'label_business_type', type: 'select', enum: "AccountModifyTypeEnum",
              listHandler: list => ['MODIFY', 'SUPPLE', 'REFUND', 'WITHDRAW', 'CONSUME', 'PAYBACK'],
            },

            { key: 'refOrderType', label: 'label_fms_subject_buss_order_type', type: 'select', enum: 'OrderTypeEnum' },

            { key: 'refOrderNo', label: 'label_fms_account_log_buss_order_no', },
            {
              key: 'happenTime', label: 'label_fms_account_log_create_time', type: 'date-picker',
              attrs: { type: 'datetime' }
            },

            { key: 'modifyLeftAmount', label: 'label_money', },
            { key: 'remark', label: 'label_fms_subject_remark', },

            {
              key: 'isUpload', label: 'label_fms_journal_voucher',
              render: (h, { data, item }) => {
                return (<ex_super_upload value={data['files']} type='image' limit={1}
                  onInput={e => {
                    this.$set(data, 'files', e);
                    console.log(e)
                  }}
                  onIsUploadChange={e => this.$set(data, 'isUpload', e)}
                  headers={{ targetFolder: 'fms/account_log' }}
                />)
              }
            },


          ],
          rules: {
            isUpload: {
              validator: (r, v, cb) => {
                if (v) {
                  cb(this.$tt("label_uploading"))
                } else {
                  cb()
                }
              }
            },
            'customerId': [{ required: true, message: this.$tt('tip_can_no_empty'), trigger: 'blur' }],
            'accountId': [{ required: true, message: this.$tt('tip_can_no_empty'), trigger: 'blur' }],
            'modifyType': [{ required: true, message: this.$tt('tip_can_no_empty'), trigger: 'blur' }],
            'happenTime': [{ required: true, message: this.$tt('tip_can_no_empty'), trigger: 'blur' }],
            'modifyLeftAmount': [{ required: true, message: this.$tt('tip_can_no_empty'), trigger: 'blur' }],
            'remark': [{ required: true, message: this.$tt('tip_can_no_empty'), trigger: 'blur' }],
          },
        }
      },
      option: {
        search: {
          model: [
            {
              label: "label_serial_number", key: "accountLogNo", attrs: { clearable: true },
            },
            {
              label: "label_fms_account_cmp_customer",
              key: "customerIds",
              type: 'common_customer_choose',
              attrs: { multiple: true, },
              inputStyle: { 'width': '200px' },
            },
            {
              label: "label_fms_account_cmp_account_type",
              key: "accountType",
              type: 'select',
              enum: 'CustomerAccountTypeEnum',
              attrs: { clearable: true },
            },
            // {
            //   label: "适用产品", key: "productType", type: 'select', enum: 'PmsProductTypeEnum', attrs: { clearable: true },
            // },
            {
              label: "label_fms_account_log_buss_type",
              key: "modifyType",
              type: 'select',
              enum: 'AccountModifyTypeEnum',
              attrs: { clearable: true },
            },
            { label: "label_business_order_code", key: "refOrderNo" },

            {
              label: "是否系统自动创建", key: "isSystemCreate", type: 'select',
              enum: 'YesOrNoEnum'
            },

            {
              label: "label_fms_account_log_create_time", key: 'happenTime1', type: 'date-picker',
              attrs: { type: 'datetime' },
              on: { change: (e) => this.happenTime1 = e },
              pickerOptions: {
                disabledDate: (date) => this.happenTime2 ? (this.happenTime2 < date.getTime()) : false
              }
            },
            {
              label: "~", key: 'happenTime2', type: 'date-picker',
              attrs: { type: 'datetime' },
              on: { change: (e) => this.happenTime2 = e },
              'pickerOptions': {
                disabledDate: (date) => this.happenTime1 ? (this.happenTime1 > date.getTime()) : false
              }
            },

          ]
        },
        action: [
          {
            label: 'label_fms_account_log_add_by_self',
            auth: "fms_account_log_add",
            click: () => {
              this.$refs.addLogDialog.showNew({
                title: this.$t("label_fms_account_log_add_by_self"),
                data: {
                  happenTime: new Date().getTime(),
                },
                onlySetData: true,
              })
            },
          },
          {
            label: 'label_import', auth: "fms_account_log_add", click: () => {
              this.importDiglogVisable = true
            },
          },
          {
            label: 'label_export', click: this.exportExcel
          }
        ],

        table: {
          url: "/fms-api/customer/CustomerAccountLogRpc/select.json",
          attrs: {
            'cell-style': ({ row, column, rowIndex, columnIndex }) => {
              if (column.property == 'status') {
                return { color: row.status == 'NORMAL' ? this.$globalCss.successColor : this.$globalCss.infoColor }
              }
            }
          },
          model: [
            { key: 'accountLogNo', label: 'label_serial_number', align: 'left' },
            {
              key: 'companyName', label: 'label_fms_account_config_customer_name', align: 'left', attrs: {
                formatter: (r, c, v, i) => {
                  return '[' + r.customerCode + '] ' + r.customerName
                }
              }
            },
            {
              key: 'isSystemCreate', label: 'label_fms_account_log_is_system_create', align: 'center', width: 120,
              attrs: {
                formatter: (r, c, v, i) => {
                  return this.$enumShow(v, 'YesOrNoEnum')
                }
              }
            },
            {
              key: 'accountType', label: 'label_fms_account_log_account', width: 200,
              attrs: {
                formatter: (r, c, v, i) => {
                  return (r.accountType == 'CREDIT' ? (this.$enumShow(r.productType, 'PmsProductTypeEnum') + '-') : '') + this.$enumShow(r.currencyType, 'CurrencyTypeEnum') + '-' + this.$enumShow(r.accountType, 'CustomerAccountTypeEnum')
                }
              }
            },
            {
              key: 'inOutType', label: 'label_fms_account_log_serial_type', align: 'center', width: 120,
              attrs: {
                formatter: (r, c, v, i) => {
                  return this.$enumShow(v, 'AccountInOutTypeEnum')
                }
              }
            },

            { key: 'serviceName', label: 'label_pms_service_cost'},
            {
              key: 'modifyType', label: 'label_fms_account_log_buss_type', align: 'center', width: 120,
              attrs: {
                formatter: (r, c, v, i) => {
                  return this.$enumShow(v, 'AccountModifyTypeEnum')
                }
              }
            },

            {
              key: 'modifyLockAmount', label: 'label_withholding_amount_change',minWidth: 140
            },
            {
              key: 'lockAmount', label: 'label_withholding_total_amount',minWidth: 140,
            },
            {
              key: 'modifyLeftAmount', label: 'label_deduction_amount',minWidth: 140,
            },
            {
              key: 'leftAmount', label: 'label_available_amount_quota',minWidth: 140,
            },
            {
              key: 'totalAmount', label: 'label_fms_account_log_total_amount',minWidth: 140,
            },
            // {
            //   key: 'freezeAmount', label: 'label_fms_account_log_account_frozen', align: 'right',
            //   attrs: {
            //     formatter: (r, c, v, i) => {
            //       return this.renderAmount(r, 'freezeAmount', 'modifyFreezeAmount')
            //     }
            //   },
            // },
            // {
            //   key: 'leftAmount', label: 'label_fms_account_log_usable_amount', align: 'right',
            //   attrs: {
            //     formatter: (r, c, v, i) => {
            //       return this.renderAmount(r, 'leftAmount', 'modifyLeftAmount')
            //     }
            //   }
            // }, {
            //   key: 'totalAmount', label: 'label_fms_account_log_total_amount', align: 'right',
            //   attrs: {
            //     formatter: (r, c, v, i) => {
            //       return this.renderAmount(r, 'totalAmount', 'modifyTotalAmount')
            //     }
            //   },
            // },
            {
              key: 'refOrderType', label: 'label_fms_account_log_buss_order_no', align: 'center', width: 230,
              attrs: {
                formatter: (r, c, v, i) => {
                  if (r.refOrderNo) {
                    return this.$enumShow(v, 'OrderTypeEnum') + '-' + r.refOrderNo
                  }
                  return '-'
                }
              }
            },
            {
              key: 'creator', label: 'label_operate_user', align: 'center', width: 200,
              // formatter: (r, c, v, i) => r.isSystemCreate==='Y'?'System':v
            },
            {
              key: 'remark', label: 'label_remark', align: 'center', width: 200,
              render: (h, { row, column }) => {
                const code = row[column.property]
                return (<text_extra_tooltip_operate
                  value={code} ellipsis
                  data_type={column.property} data_id={row.id}
                />)
              },
            },
            {
              key: 'happenTime', label: 'label_fms_account_log_create_time', width: 160, attrs: {
                formatter: (r, c, v, i) => {
                  return this.$dateFormat(v)
                }
              }
            },
            {
              key: 'gmtCreate', label: 'label_create_time', width: 160, attrs: {
                formatter: (r, c, v, i) => {
                  return this.$dateFormat(v)
                }
              }
            },
            {
              type: 'operate', width: 120,
              operate: [
                {
                  if: (row) => {
                    return row.billDetailId || row.refOrderType === 'BILL'
                  },
                  label: '费用明细',
                  if: (row) => row.isSystemCreate == "Y",
                  click: (row) => {
                    if (row.billDetailId) {
                      this.feeDetail(row)
                    }
                    if (row.refOrderType === 'BILL') {
                      this.routeToBillDetail(row)
                    }
                  }
                },
                {
                  label: 'label_fms_account_pay_photo',
                  if: (row) => !!row.logVoucher,
                  click: (row) => {
                    this.previewUrls = [row.logVoucher]
                    // this.showViewer
                    this.$refs.previewImage.$refs.img.showViewer = true
                    // console.log(this.$refs.previewImage)
                  }
                }
              ],
            }
          ]
        }
      }
    };
  },
  created() {

  },

  props: {},

  destroyed() {

  },

  methods: {
    routeToBillDetail(row) {

      this.$ajax({
        url: '/fms-api/customer/CustomerBillRpc/detailByNo.json?billNo=' + row.refOrderNo,
        success: (res) => {
          if (res && res.data) {
            this.$router.push({
              path: '/page/fms/income/bill_view',
              query: { id: res.data.id, no: row.refOrderNo }
            })
          }
        }
      });

    },
    feeDetail(row) {
      this.chooseRowBillDetailId = row.billDetailId
      this.dialogVisible = true
    },

    renderAmount(r, totalField, modifyField) {
      let str = r[totalField]
      if (r[modifyField] && r[modifyField] != 0) {

        if (r[modifyField] > 0) {
          str += ' (+' + r[modifyField] + ')'
        } else {
          str += ' (' + r[modifyField] + ')'
        }
      }
      return str
    },


    submitForm() {

      let _this = this

      _this.$refs['formEl'].validate((valid) => {
        if (valid) {

          _this.$ajax({
            url: '/fms-api/customer/CustomerCreditApplyRpc/audit.json',
            // type: 'json',
            data: _this.formValue,
            success: (responseData) => {
              this.$message({
                showClose: true,
                message: this.$tt('tip_submit_success'),
                type: 'success'
              })
              _this.$refs['SuperTablePage'].reload()
              _this.dialogFormVisible = false
            }
          });

        } else {
          return false;
        }

      });

    },


    accountLogAddBySelf() {
      let _this = this

      _this.$refs['formEl'].validate((valid) => {
        if (valid) {

          _this.$ajax({
            url: '/fms-api/customer/CustomerAccountLogRpc/saveAccountLogBySelf.json',
            type: 'json',
            data: _this.formValue,
            success: (responseData) => {
              this.$message({
                showClose: true,
                message: this.$tt('tip_submit_success'),
                type: 'success'
              })
              _this.$refs['SuperTablePage'].reload()
              _this.addLogDialogVisible = false
            }
          });

        } else {
          return false;
        }

      });
    },

    downloadImportTemp() {
      if (this.$clickFast()) return
      this.$downloadFile({
        loading: true,
        url: '/fms-api/customer/CustomerAccountLogRpc/downloadImportTemp.json',
      })
    },
    uploadFile(cfg) {
      this.$uploadFile({
        loading: true,
        url: '/fms-api/customer/CustomerAccountLogRpc/importExcel.json',
        file: cfg.file,
        success: (res) => {
          this.$emitPage("oms>import_manage", 'reload')
          this.importDiglogVisable = false
          this.$confirm(this.$tt("tip_importing_confirm_goto_recode_list"), this.$tt('label_tip'), {
            type: 'success'
          }).then(() => {
            this.$router.push({
              path: '/page/oms/report/import_manage',
            });
          }).catch(() => {
          });
        }
      })
    },
    exportExcel() {
      business_function.confirmOperateBaseSelectOrForm.call(this, {
        data: this.$refs.SuperTablePage.getSearchFormData(),
        model: this.option.search.model,
        selection: this.selection,
        callback: (selection, data) => {
          let params = {}
          if (!_.isEmpty(selection)) {
            params = {
              idList: selection.map(it => it.id)
            }
          } else {
            params = data
          }
          this.$functionCommon({
            url: '/fms-api/customer/CustomerAccountLogRpc/export.json',
            data: params
          })
        }
      })
    },


  }
};

</script>
<style>
.small-btn span {
  font-size: 14px;
}

.small-btn .el-button--small span {
  font-size: 14px;
}
</style>
